package animix.blue.server.user.service.impl;


import animix.blue.server.common.bean.pojo.Result;
import animix.blue.server.common.bean.model.Role;
import animix.blue.server.common.bean.model.RoleRight;
import animix.blue.server.user.mapper.RoleMapper;
import animix.blue.server.user.mapper.RoleRightMapper;
import animix.blue.server.user.service.RoleRightService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class RoleRightServiceImpl implements RoleRightService {

    @Autowired
    private RoleMapper roleMapper;

    @Autowired
    private RoleRightMapper roleRightMapper;

    @Override
    public Result getRightIdsByRoleId(Integer roleId) {
        // id验证
        Result result = getRoleById(roleId);
        if (result.getCode() != 200) {
            return result;
        }
        // 查询
        List<RoleRight> roleRightList = roleRightMapper.listByRoleId(roleId);
        // 组织返回数组
        if (roleRightList != null && roleRightList.size() > 0) {
            Integer[] rightIds = new Integer[roleRightList.size()];
            rightIds = roleRightList.stream().map(RoleRight::getRightId).toArray(Integer[]::new);
            return Result.ok(rightIds);
        } else {
            return Result.ok(new Integer[]{});
        }
    }

    @Transactional
    @Override
    public Result setByRoleId(Integer roleId, Integer[] rightIds) {
        // id验证
        Result result = getRoleById(roleId);
        if (result.getCode() != 200) {
            return result;
        }
        // 删除
        roleRightMapper.deleteByRoleId(roleId);
        // 插入
        if (rightIds != null && rightIds.length > 0) {
            List<RoleRight> roleRightList = new ArrayList<>();
            for (int i = 0; i < rightIds.length; i++) {
                RoleRight roleRight = new RoleRight();
                roleRight.setRoleId(roleId);
                roleRight.setRightId(rightIds[i]);
                roleRight.setCreated(new Date());
                roleRight.setUpdated(new Date());
                roleRightList.add(roleRight);
            }
            roleRightMapper.insertBatch(roleRightList);
        }
        return Result.ok();
    }

    private Result getRoleById(Integer id) {
        if (id != null) {
            Role role = roleMapper.getById(id);
            if (role != null) {
                return Result.ok(role);
            } else {
                return Result.build(400, "id不存在！");
            }
        } else {
            return Result.build(400, "id无效！");
        }
    }
}
